package handler;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Hyperlink;

import java.util.List;

public class SheetLinkCellWriteHandler implements CellWriteHandler {
    /**
     * 给表名添加链接到对应的sheet上
     */
    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        // 第一列第二行开始
        if (cell.getRowIndex() >= 1 && cell.getColumnIndex() == 1) {

            CreationHelper helper = writeSheetHolder.getSheet().getWorkbook().getCreationHelper();

            // 设置本文档内sheet链接，需要类型为HyperlinkType.DOCUMENT
            Hyperlink hyperlink = helper.createHyperlink(HyperlinkType.DOCUMENT);

            // #sheet名!A1   #：表示本文档 sheet名：sheet的名称 !A1：链接到该sheetA1单元格
            hyperlink.setAddress("#" + cell.getStringCellValue() + "!A1");

            cell.setHyperlink(hyperlink);
        }
    }
}
